#include "spritemonster.h"
#include "pixelfontblitter.h"

int main (int argc, char ** argv)
{
	// [INIT]
	// TODO load these from a settings file?
	int SCREEN_WIDTH = 800;
	int SCREEN_HEIGHT = 600;
	int SCREEN_BPP = 32;
	int FPS = 40;
	int FPS_DELAY = 1000/FPS;
	// main state of the main loop
	bool running = true;
	SRect appScreenSize(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
	if (SDL_Init( SDL_INIT_VIDEO ) != 0)
	{
		printf( "Unable to init SDL: %s\n", SDL_GetError());
		running = false;
	}
    // ensure a clean exit
    atexit(SDL_Quit);
    // create a new window
    SDL_Surface* screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP,
                                           SDL_HWSURFACE|SDL_DOUBLEBUF);
    SDL_WM_SetCaption("SpriteMonster v0.0.4", 0);
    if (!screen) {
        printf("Unable to set %dx%d (%dbpp) video: %s\n", 
			SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_GetError());
        running = false;
    }
	// event
	SDL_Event e;
	// timing variables
	Uint32 now, then = SDL_GetTicks(), passed, soon;

	// create sprite editing application (must happen after SDL initializes)
	SpriteMonster monster;
	monster.init(appScreenSize);
	if(argc <= 1){
		printf("Usage: spritemonster <spritefile> [bitmapimages...]\n"
			"to edit a <spritefile> using the listed bitmap images\n");
	}else{
		// parse the parameters (load files)
		for(int i = 1; i < argc; ++i)
		{
			monster.load(argv[i]);
		}
	}

	SDL_Surface * fontImage = VSDL_loadImage(
//		"sprites/ascii.bmp"
		"sprites/arial.bmp");
//	PixelFont f;
//	f.setVariableWidthAscii(fontImage, ' ', 95);
//	PixelFontArea pfb(&f, SRect(30,30,200,200), 10, 20, DV_SDLConsoleMode::Stream, screen);

	// [GAME LOOP]
	while(running)
	{
		// [UPDATE]
		// timing
		now = SDL_GetTicks();
		passed = now - then;
		then = now;
		// update the app based on timing. may result in dirty rectangles being created...
		monster.update(passed);
//		pfb.update(passed);

		// [DRAW]
		// if something changed in the game
		if(monster.isDirty())
		{
			// draw the new state
			monster.draw(screen);
			// flip the screen
			SDL_Flip(screen);
		}

//		pfb.draw(screen);
//		SDL_Flip(screen);

		// throttle code - wait until there is input
		soon = SDL_GetTicks() + FPS_DELAY;
		while(!SDL_PollEvent(0) && SDL_GetTicks() < soon){SDL_Delay(1);}

		// [INPUT]
		// process all events
		while(SDL_PollEvent(&e))
		{
			switch(e.type)
			{
			// QUIT must be processed-- Now.
			case SDL_QUIT:	running = false;	break;
			// other app events can wait a bit.
			default:
//				pfb.handleSDL(e);
				monster.queueEvent(e);
			}
		}
		if(!monster.isRunning())
			running = false;
    }
	// [RELEASE]
	SDL_FreeSurface(fontImage);
	// manual cleanup
	monster.release();
	// clean up the rest of the SDL framework
	SDL_Quit();
    return 0;
}
